using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Threading.Tasks;
using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Plugin;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace PdfOperationCommand
{
    [Icon("pack://application:,,,/PdfOperationCommand;component/Resources/Merge.png")]
    [OrderWeight(2)]
    [Description("合并PDF文件，使用iTextSharp实现")]
    public class PdfMergeServerCommand : BaseServerCommand, ICommandExecutableInServerSideAsync
    {
        [Required]
        [FormulaProperty]
        [DisplayName("待合并文件路径列表（数组）")]
        [Description("文件绝对路径数组，如：D:\\example.pdf(Windows)，/path/example.pdf(Linux)")]
        public object FilePaths { get; set; }

        [Required]
        [FormulaProperty]
        [DisplayName("输出文件路径")]
        [Description("文件绝对路径，如：D:\\example.pdf(Windows)，/path/example.pdf(Linux)")]
        public object OutFilePath { get; set; }

        public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            var outFilePath = await GetParamValue(dataContext, OutFilePath);

            using (var document = new Document())
            {
                using (var copy = new PdfCopy(document, new FileStream(outFilePath.ToString(), FileMode.Create)))
                {
                    document.Open();
                    var filePaths = await GetArrayListParam(dataContext, FilePaths);
                    foreach (var inputFile in filePaths)
                    {
                        using var reader = new PdfReader(inputFile?.ToString());
                        for (var i = 1; i <= reader.NumberOfPages; i++)
                        {
                            var page = copy.GetImportedPage(reader, i);
                            copy.AddPage(page);
                        }
                    }
                }
            }

            return new ExecuteResult();
        }

        public override string ToString()
        {
            return "合并PDF文件";
        }
    }
}